package parkshop.pmcourse.controller;


import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import parkshop.pmcourse.domain.OrderComment;
import parkshop.pmcourse.domain.Orderdetail;
import parkshop.pmcourse.domain.Orders;
import parkshop.pmcourse.domain.Product;
import parkshop.pmcourse.dto.PageBean;
import parkshop.pmcourse.dto.User;
import parkshop.pmcourse.service.OrdersService;
import parkshop.pmcourse.service.ProductService;
import parkshop.pmcourse.service.ShoppingCartService;
import parkshop.pmcourse.utils.ConstantUtil;

@Controller
@RequestMapping("/order")
public class OrderContrller {
	
	@Autowired
	private OrdersService ordersService;
	
	@Autowired
	private ProductService productService;
	@Autowired
	private ShoppingCartService shoppingCartService;
	
	
	@PostMapping("/toConfirmOrder")
	 public String toConfirmOrder(Integer productId, int quantity, Model model, HttpSession httpSession, HttpServletRequest request, HttpServletResponse response){
		User customer = (User) httpSession.getAttribute(ConstantUtil.nameOfCurUser);
		if (customer == null) {
			try {
				response.sendRedirect(request.getContextPath() + "/signin");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		} else {
			Product product = productService.getProductById(productId);
			model.addAttribute("product", product);
			model.addAttribute("customer", customer);
			model.addAttribute("quantity", quantity);
			model.addAttribute("totalMoney", product.getPrice()*quantity);
			return "confirmOrder";
		}
	 }
	
	@PostMapping("/submitOrder")
	 public String submitOrder(Orders orders, Orderdetail orderdetail,Model model){
		orders.setOrderTime(new Date(System.currentTimeMillis()));
		orders.setOrderStatus(ConstantUtil.orderStatus_unpay);
		orders.setCommissionRates(ConstantUtil.commissionRate);
		List<Orderdetail> list = new ArrayList<Orderdetail>();
		list.add(orderdetail);
		Product product=productService.getProductById(orderdetail.getProductId());
		product.setInventory(product.getInventory()-(orderdetail.getQuantity()==null?1:orderdetail.getQuantity()));
		productService.updateProduct(product);
		ordersService.saveOrder(orders, list);
		
		model.addAttribute("orderdetail", orderdetail);
		model.addAttribute("orders", orders);
		model.addAttribute("product", ordersService.getOrderProduct(orders.getId()));
		return "customer/needPayment";
	 }
	
	/*
	 *  买家和卖家共用，根据 session区分
	 */
	@GetMapping("/list/{pageNumber}")
	 public String listOrders(@PathVariable int pageNumber,Model model,HttpServletRequest request){
		User curUser=(User) request.getSession(false).getAttribute(ConstantUtil.nameOfCurUser);
		PageBean pageBean = ordersService.selectAllOrdersByUser(pageNumber, curUser.getType(), curUser.getId());

		model.addAttribute("pageBean", pageBean);
		return "shopOwner/orderManage";
	 }
	@GetMapping("/list/{statusNumber}/{pageNumber}")
	public String listStatusOrders(@PathVariable int statusNumber,@PathVariable int pageNumber,Model model,HttpServletRequest request){
		User curUser=(User) request.getSession(false).getAttribute(ConstantUtil.nameOfCurUser);
		PageBean pageBean = ordersService.selectSpecificStatusOrdersByUser(pageNumber, curUser.getType(), curUser.getId(),statusNumber);
		
		model.addAttribute("pageBean", pageBean);
		model.addAttribute("status", statusNumber);
		return "shopOwner/orderManage";
	}
	
	@PostMapping("/payment/paying")
	public String pay(int orderId,Long cartId,Model model, HttpServletRequest request){
		User curUser=(User) request.getSession(false).getAttribute(ConstantUtil.nameOfCurUser);
		if(orderId==ConstantUtil.shoppingCartOrderId){// 来自购物车的订单
			shoppingCartService.payShoppingCart(cartId);
			return "redirect:/customer/shoppingcart/list/1";
		}
		
		Orders order=ordersService.paying((long) orderId, curUser);	
		Product product=ordersService.getOrderProduct(order.getId());
		Orderdetail detail=ordersService.getOrderDetailByOrderId(order.getId());
		order.setImageUrl(product.getImageUrl());
		order.setProductName(product.getName());
		order.setProductId(product.getId());
		order.setQuantity(detail.getQuantity());
		model.addAttribute("pageBean", oneOrderToPageBean(order));
		model.addAttribute("status", ConstantUtil.orderStatus_unshiped);
		return "shopOwner/orderManage";		
	}
	@GetMapping("/payment/{orderId}")
	public String goPay(@PathVariable int orderId,Model model, HttpServletRequest request){
		
		Orders orders=ordersService.getOrderByOrderId((long) orderId);

		model.addAttribute("product", ordersService.getOrderProduct(orders.getId()));
		model.addAttribute("orders", orders);
		return "customer/needPayment";
	}
	@GetMapping("/deliver/{orderId}")
	public String deliver(@PathVariable long orderId,Model model, HttpServletRequest request){
		
		Orders order=ordersService.deliver(orderId);
		model.addAttribute("pageBean", oneOrderToPageBean(order));
		model.addAttribute("status", ConstantUtil.orderStatus_unreceived);
		return "shopOwner/orderManage";
	}
	@GetMapping("/receive/{orderId}")
	public String received(@PathVariable int orderId,Model model, HttpServletRequest request){
		
		Orders order=ordersService.received((long) orderId);
		model.addAttribute("pageBean", oneOrderToPageBean(order));
		model.addAttribute("status", ConstantUtil.orderStatus_unfinish);
		return "shopOwner/orderManage";
	}
	private PageBean oneOrderToPageBean(Orders order){
		PageBean pageBean=new PageBean();
		List<Orders> list=new ArrayList<Orders>();
		Orderdetail detail=ordersService.getOrderDetailByOrderId(order.getId());
		Product product=productService.getProductById(detail.getProductId());
		
		order.setQuantity(detail.getQuantity());
		order.setImageUrl(product.getImageUrl());
		order.setProductName(product.getName());
		
		list.add(order);
		pageBean.setRecordList(list);
		pageBean.setPageCount(1);
		pageBean.setCurrentPage(1);
		pageBean.setRecordCount(1);
		return pageBean;
	}
	
	@GetMapping("/income")
	public String getIncome(Model model, HttpServletRequest request){
		User user=(User) request.getSession().getAttribute(ConstantUtil.nameOfCurUser);
		JSONObject json=new JSONObject();
		float[] dayIncomes=ordersService.getIncomeByDate(Calendar.DAY_OF_YEAR, user);
		float[] weekIncomes=ordersService.getIncomeByDate(Calendar.WEEK_OF_YEAR, user);
		float[] monthIncomes=ordersService.getIncomeByDate(Calendar.MONTH, user);
		float[] yearIncomes=ordersService.getIncomeByDate(Calendar.YEAR, user);
		json.put("dayIncome", dayIncomes);
		json.put("weekIncome", weekIncomes);
		json.put("monthIncome", monthIncomes);
		json.put("yearIncome", yearIncomes);
		model.addAttribute("income", json);
		return "shopOwner/incomeInfo";
	}
	
	@PostMapping("/income")
	public void getChoiceDateIncome(String date,int type,Model model, HttpServletRequest request,HttpServletResponse response) throws IOException{
		User user=(User) request.getSession().getAttribute(ConstantUtil.nameOfCurUser);
		JSONObject json=new JSONObject();
		Date date1=Date.valueOf(date);
		float[] incomes=ordersService.getIncomeBySpecialDate(date1, type, user);
		String key="";
		switch(type){
		case Calendar.DAY_OF_YEAR:
			key="dayIncome";
			break;
		case Calendar.WEEK_OF_YEAR:
			key="weekIncome";
			break;
		case Calendar.MONTH:
			key="monthIncome";
			break;
		case Calendar.YEAR:
			key="yearIncome";
			break;
		}
		json.put(key, incomes);
		response.getWriter().write(json.toString());
	}
	
	@GetMapping("/comment/{orderId}")
	public String goComment(@PathVariable Long orderId,Model model, HttpServletRequest request){
		Product product=ordersService.getOrderProduct(orderId);
	    model.addAttribute("orderDetail", ordersService.getOrderDetailByOrderId(orderId));
		model.addAttribute("product",product);
		return "customer/orderComment";
	}
	
	@PostMapping("/comment")
	public String comment(OrderComment comment,Model model, HttpServletRequest request){
		
		ordersService.saveOrderComment(comment);
		
		return "redirect:/order/list/3/1";
	}
	@PostMapping("/search")
	public String search(String fromTime,String toTime,int status,Model model, HttpServletRequest request) throws ParseException{
		User user=(User) request.getSession().getAttribute(ConstantUtil.nameOfCurUser);
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//Date from = sdf.parse(fromTime+" 00:00:00");
		Date from = Date.valueOf(fromTime);
		Date to = Date.valueOf(toTime);
		System.out.println(new Date(System.currentTimeMillis()));
		PageBean pageBean=ordersService.getOrdersByDate(from, to, user, status);
		model.addAttribute("pageBean", pageBean);
		model.addAttribute("status", status);
		return "shopOwner/orderManage";
	}
	@GetMapping("/delete/{orderId}")
	public String delete(@PathVariable Long orderId,Model model, HttpServletRequest request) throws ParseException{
		User user=(User) request.getSession().getAttribute(ConstantUtil.nameOfCurUser);
		Orders order=ordersService.getOrderByOrderId(orderId);
		ordersService.deleteOrderById(orderId);
		if(order!=null){
		model.addAttribute("status", order.getOrderStatus());
		return "redirect:/order/list/"+order.getOrderStatus()+"/1";
		}
		return "redirect:/order/list/1/1";
	}
	
}
